<template>
  <van-dialog
    v-model:show="showDialog"
    :title="props.title"
    show-cancel-button
    :before-close="handleBeforeClose"
    @closed="handleClosed"
  >
    <van-form ref="formRef">
      <van-cell-group>
        <van-field
          v-model="textarea"
          rows="2"
          autosize
          type="textarea"
          maxlength="50"
          placeholder="请输入"
          show-word-limit
          :rules="[{ required: true, message: '请输入' }]"
        />
      </van-cell-group>
    </van-form>
  </van-dialog>
</template>

<script lang="ts">
export default {
  name: 'DialogTextarea'
}
</script>

<script setup lang="ts">
import { Dialog } from 'vant'
import { ref, computed } from 'vue'
import type { FormInstance } from 'vant'
const VanDialog = Dialog.Component

const props = defineProps({
  show: {
    type: Boolean,
    required: true
  },
  title: {
    type: String,
    default: '不通过原因'
  },
  successCallback: {
    type: Function,
    default() {
      return true
    }
  },
  errorCallBack: {
    type: Function,
    default() {
      return false
    }
  },
  cancelCallBack: {
    type: Function,
    default() {
      return true
    }
  }
})

const formRef = ref<FormInstance>()

const emit = defineEmits(['update:show'])

const showDialog = computed({
  get() {
    return props.show
  },
  set(val: boolean) {
    emit('update:show', val)
  }
})

const textarea = ref('')

defineExpose({
  textarea
})

const handleBeforeClose = (action: 'confirm' | 'cancel') => {
  if (action === 'confirm') {
    return formRef.value
      ?.validate()
      .then(() => {
        return props.successCallback()
      })
      .catch(() => {
        return props.errorCallBack()
      })
  } else {
    return props.cancelCallBack()
  }
}

const handleClosed = () => {
  textarea.value = ''
}
</script>
<style lang="scss" scoped>
.van-cell-group {
  margin: 15px;
}
.van-field {
  border: 1px solid #eee;
}
</style>
